﻿using System;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using RuTracker.Interface;
using RuTracker.MVC.Core;
using RuTracker.MVC.Models.Tracker;
using RuTrackerLib;
using RuTrackerLib.Tracker;
using RuTrackerLib.Tracker.RequestProcessors;

namespace RuTracker.MVC.Controllers
{
    [Authorize]
    public class DefaultController : Controller
    {
        public ActionResult Index()
        {
            if (!DoesUserContainSettings())
                return RedirectToAction("Index", "Settings");

            return RedirectToAction("Tracker");
        }

        public ActionResult Tracker(string query)
        {
            string url = QueryStringEncryptor.Decrypt(query);
            string queryString = Request.QueryString.Keys.Cast<string>().Where(key => key != "query").Aggregate(string.Empty, (current, key) => current + string.Format("&{0}={1}", key, Request.QueryString[key]));
            if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(queryString))
            {
                url += queryString;
                return RedirectToAction("Tracker", new {query = QueryStringEncryptor.Encrypt(url)});
            }

            IRequestProcessor processor = Container.Current.Resolve<IRequestProcessor>();
            TrackerModelFactory modelFactory = new TrackerModelFactory(Container.Current);

            RequestProcessingResults processingResult = processor.ProcessRequest(url, User.Identity.Name);
            TrackerModel model = modelFactory.Create(processingResult, User, url);


            if (processingResult.IsLoginRequired)
                return RedirectToAction("Index", "Authorize");


            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Tracker(TrackerModel model)
        {
            string searchQuery = string.Format("query={0}", model.SearchQuery);
            string siteRootPath = ConfigurationManager.AppSettings["SiteRootPath"];
            string redirectUrl = string.Format("{0}/Default/Tracker?query={1}", siteRootPath, QueryStringEncryptor.Encrypt(searchQuery));
            return Redirect(redirectUrl);
        }

        private bool DoesUserContainSettings()
        {
            IUserRepository repository = Container.Current.Resolve<IUserRepository>();
            var storageInfo = repository.GetUserStorageInfo(User.Identity.Name);
            return storageInfo != null
                   && !string.IsNullOrEmpty(storageInfo.StorageFolder)
                   && storageInfo.Token != null;
        }
    }
}
